package customer

import (
	"fmt"
	"go.uber.org/zap"
	"server/global"
	CustomerModel "server/model/customer"
	customerReq "server/model/customer/request"
	customerRes "server/model/customer/response"
)

// GetPeople 获取人员列表
func (cs *CustomerService) GetPeople(PeopleSp customerReq.PeopleSearchParams) ([]customerRes.PeopleResult, int64, error) {
	var peopleResult []customerRes.PeopleResult
	var total int64

	db := global.TD27_DB.Model(&CustomerModel.PeopleModel{}).
		Order("people.updated_at DESC")

	if PeopleSp.Name != "" {
		db = db.Where("people.name LIKE ?", "%"+PeopleSp.Name+"%")
	}

	err := db.Count(&total).Error
	if PeopleSp.PageSize != 0 || PeopleSp.Page != 0 {
		db.Limit(PeopleSp.PageSize).Offset(PeopleSp.PageSize * (PeopleSp.Page - 1))
	}
	db.Find(&peopleResult)
	if err != nil {
		return peopleResult, total, fmt.Errorf("查询 PeopleModel 失败: %v", err)
	}
	// 返回结果
	return peopleResult, total, nil
}

// AddOrUpdatePeople 添加/更新人员信息
func (cs *CustomerService) AddOrUpdatePeople(people customerReq.People) (*customerRes.PeopleResult, string, error) {
	var peopleModel CustomerModel.PeopleModel
	var peopleResult customerRes.PeopleResult
	var action string

	if people.ID == 0 {
		action = "添加"
		// 创建新的 peopleModel 对象
		peopleModel = CustomerModel.PeopleModel{
			Name:     people.Name,
			JobTitle: people.JobTitle,
			Status:   people.Status,
		}

		// 执行添加操作
		if err := global.TD27_DB.Create(&peopleModel).Error; err != nil {
			return nil, action, err
		}
	} else {
		action = "修改"
		//// 根据 people.ID 查询对应的 PeopleModel 对象
		if err := global.TD27_DB.First(&peopleModel, people.ID).Error; err != nil {
			global.TD27_LOG.Error("编辑人员 -> 查询Id", zap.Error(err))
			return nil, action, err
		}
		//
		//// 更新 peopleModel 对象的属性值
		peopleModel.Name = people.Name
		peopleModel.JobTitle = people.JobTitle
		peopleModel.Status = people.Status

		// 执行修改操作
		if err := global.TD27_DB.Save(&peopleModel).Error; err != nil {
			global.TD27_LOG.Error("编辑人员 -> update", zap.Error(err))
			return nil, action, err
		}
	}

	// 构造返回结果
	peopleResult.ID = peopleModel.ID
	peopleResult.UpdatedAt = peopleModel.UpdatedAt
	peopleResult.Name = peopleModel.Name
	peopleResult.JobTitle = peopleModel.JobTitle
	peopleResult.Status = peopleModel.Status

	return &peopleResult, action, nil
}
